<template>
  <div class="monitor-container">
    <!-- <div style="width: 50px; height: 50px; position: fixed; top: 0; left: 0; z-index: 100000; background-color: #f00" @click="mockAIS"></div> -->
    <HeadCard @menuSelect="menuSelect" />
    <MapCard ref="mapRef" />
    <div class="monitor-left">
      <!-- 关注列表 -->
      <Follow ref="followRef" @rowSelect="followSelect" @eventHistory="eventHistory" @flickerArea="flickerArea" />
      <!-- 报警列表 -->
      <Alarm ref="alarmRef" @rowSelect="followSelect" @eventHistory="eventHistory" @flickerArea="flickerArea" />
      <!-- 黑名单 -->
      <WatchRecord ref="watchRecordRef" @rowSelect="blackSelect" />
    </div>
    <div class="monitor-right">
      <!-- 实时监控 -->
      <RealVideo ref="realVideoRef" />
      <!-- 子监控列表 -->
      <CameraList @cameraSelect="cameraSelect" />
    </div>
    <div class="monitor-center" v-if="false">
      <!-- 预警统计 -->
      <Warning />
    </div>
    <!-- 设备列表 -->
    <div class="monitor-device">
      <DeviceList ref="deviceRef" @select="deviceSelect" />
    </div>
    <!-- 桥梁配置 -->
    <AisConfig ref="aisRef" />
    <!-- 水位计 -->
    <WaterConfig ref="waterRef" />
    <!-- 区域配置 -->
    <AreaConfig ref="areaRef" @uploadConfig="uploadConfig" />
    <!-- 大桥配置 -->
    <BridgeConfig ref="bridgeRef" />
    <!-- 摄像头配置 -->
    <CameraConfig ref="cameraRef" @uploadConfig="uploadConfig" />
    <!-- 雷达配置 -->
    <RadarConfig ref="radarRef" @uploadConfig="uploadConfig" />
    <!-- 策略配置 -->
    <StrategyConfig ref="strategyRef" />
    <!-- 策略配置 -->
    <ShipConfig ref="shipRef" />
    <!-- 流量流向统计 -->
    <TrafficConfig ref="trafficConfigRef" />
    <!-- 归档配置 -->
    <ArchivesConfig ref="archivesRef" />
    <!-- 关注详情 -->
    <AlarmDetail ref="alarmDetailRef" v-if="detailShow" @close="detailClose" @download="downloadVideo" />
    <!-- 统计 - 流量 -->
    <TrafficStatistics ref="trafficRef" />
    <!-- 统计 - 事件 -->
    <EventStatistics ref="eventCountRef" />
    <!-- 下载列表 -->
    <DownloadTips ref="downloadTipsRef" />
  </div>
</template>
<script setup>
  // components
  import HeadCard from './components/head/index.vue';
  import MapCard from './components/map/index.vue';
  import Follow from './components/follow/index.vue';
  import Alarm from './components/alarm/index.vue';
  import RealVideo from './components/realVideo/index.vue';
  import CameraList from './components/cameraList/index.vue';
  import Warning from './components/warning/index.vue';
  import DeviceList from './components/deviceList/index.vue';
  import AlarmDetail from './components/alarmDetail/index.vue';
  import WatchRecord from './components/watchRecord/index.vue';
  import DownloadTips from '/@/components/downloadTips/index.vue';
  // config
  import AisConfig from './components/config/ais/index.vue';
  import WaterConfig from './components/config/waterLine/index.vue';
  import AreaConfig from './components/config/area/index.vue';
  import BridgeConfig from './components/config/bridge/index.vue';
  import CameraConfig from './components/config/camera/index.vue';
  import RadarConfig from './components/config/radar/index.vue';
  import StrategyConfig from './components/config/strategy/index.vue';
  import ShipConfig from './components/config/ship/index.vue';
  import TrafficConfig from './components/config/traffic/index.vue';
  import ArchivesConfig from './components/config/archives/index.vue';
  // statistics
  import TrafficStatistics from './components/statistics/traffic/index.vue';
  import EventStatistics from './components/statistics/event/index.vue';
  // js
  import { ref, onMounted, nextTick } from 'vue';
  import MqttJS from './js/mqtt.js';
  import { dateFormat } from '/@/utils/date.js';
  import { useUserStore } from '/@/store/modules/system/user';
  // api
  import { api as aisTrackApi } from '/@/api/plat/ais-track.js';
  import { api as gbRecordApi } from '/@/api/wvp/gb_record.js';
  import { api as cameraApi } from '/@/api/plat/camera.js';
  import { api as eventApi } from '/@/api/plat/event.js';

  const mapRef = ref();
  const followRef = ref();
  const alarmDetailRef = ref();
  const aisRef = ref();
  const waterRef = ref();
  const areaRef = ref();
  const bridgeRef = ref();
  const cameraRef = ref();
  const radarRef = ref();
  const deviceRef = ref();
  const strategyRef = ref();
  const realVideoRef = ref();
  const alarmRef = ref();
  const trafficRef = ref();
  const eventCountRef = ref();
  const alarmCountRef = ref();
  const shipRef = ref();
  const archivesRef = ref();
  const trafficConfigRef = ref();
  const downloadTipsRef = ref();
  const toolTipRef = ref();
  const watchRecordRef = ref();
  const detailShow = ref(false);
  // mqtt对象
  let MqttTarget = null;
  // mqtt topic列表
  const topicList = [
    {
      topic: '/event/start',
      fn: evenStart,
    },
    {
      topic: '/event/end',
      fn: eventEnd,
    },
    {
      topic: '/fusion/lost',
      fn: shipLost,
    },
    {
      topic: '/fusion/point/#',
      fn: mqttGetGps,
      key: '/fusion/point/',
    },
    {
      topic: '/light/track/#',
      fn: changeCamera,
      key: '/light/track/',
    },
    {
      topic: '/light/stop/#',
      fn: stopCamera,
      key: '/light/stop/',
    },
    {
      topic: '/ais/lost',
      fn: shipLost,
    },
    {
      topic: '/water/value',
      fn: mqttGetWaterValue,
    },
    {
      topic: '/event/illegal',
      fn: eventIllegal,
    },
    {
      topic: '/device/ping/#',
      fn: devicePing,
      key: '/device/ping/',
    },
    {
      topic: '/watch/black/#',
      fn: mqttGetWatchRecord,
      key: '/watch/black/',
    },
  ];

  function deviceSelect(row) {
    mapRef.value.deviceSelect(row);
    // 如果是摄像头，要去切换视频播放
    console.log('row: ', row);
    if (row.deviceType === '1') {
      cameraApi.getDetailById(row.deviceId).then(({ data }) => {
        cameraSelect(data);
      });
    }
  }

  function shipLost(row) {
    mapRef.value.removeShipByMqtt(row);
  }

  function downloadVideo(row) {
    gbRecordApi
      .downloadVideo({
        url: row.playbackStreamUrl,
        startTime: row.startTime,
        endTime: row.endTime,
      })
      .then(({ data }) => {
        let streamInfo = data;
        downloadTipsRef.value.openDialog(row.playbackStreamUrl, streamInfo);
      });
  }

  function initMqtt() {
    MqttJS.createConnection(topicList).then((res) => {
      MqttTarget = res;
      MqttTarget.on('message', (topic, message) => {
        const row = JSON.parse(MqttJS.Uint8ArrayToString(message));
        for (let item of topicList) {
          if (topic.indexOf(item.key || item.topic) > -1) {
            item.fn(row);
          }
        }
      });
    });
  }

  function mqttGetGps(row) {
    if (!row.targetId) {
      row.targetId = row.mmsi || 0;
    }
    mapRef.value.mqttGetGps(row);
  }

  function evenStart(row) {
    if (row.eventType === '0') {
      followRef.value.getDataByMqtt(row);
    } else {
      alarmRef.value.getDataByMqtt(row);
    }
    // 通知区域开始闪烁 0 关注 1报警
    // mapRef.value.flickerArea([{ ...row, state: row.eventType }], row.eventType);
    getFlickerArea();
  }

  function eventEnd(row) {
    followRef.value.reloadDataByMqtt(row);
    alarmRef.value.reloadDataByMqtt(row);
    setTimeout(() => {
      getFlickerArea();
    }, 1 * 1000);
  }

  function getFlickerArea() {
    eventApi
      .queryList({
        startTime: dateFormat(new Date(), 'yyyy-MM-dd ' + '00:00:00'),
        endTime: dateFormat(new Date(), 'yyyy-MM-dd ' + '23:59:59'),
      })
      .then(({ data }) => {
        let list = [];
        for (let item of data) {
          if (item.eventType === '0' && !item.endTime) {
            item.state = item.eventType;
            list.push(item);
          }
          if (!item.endTime && item.eventType === '1' && item.isEnabled) {
            item.state = item.eventType;
            list.push(item);
          }
        }
        mapRef.value.flickerArea(list);
      });
  }

  // 绘制闪烁的区域
  function flickerArea(list, state) {
    // mapRef.value.flickerArea(list, state);
    // getFlickerArea();
  }

  function menuSelect(val) {
    const menuList = {
      ais: aisRef,
      water: waterRef,
      area: areaRef,
      bridge: bridgeRef,
      camera: cameraRef,
      radar: radarRef,
      strategy: strategyRef,
      traffic: trafficRef,
      event: eventCountRef,
      alarm: alarmCountRef,
      trafficConfig: trafficConfigRef,
      ship: shipRef,
      archives: archivesRef,
    };
    menuList[val].value.open();
  }

  function followSelect(val) {
    detailShow.value = true;
    nextTick(() => {
      alarmDetailRef.value.open(val);
    });
  }

  function detailClose() {
    detailShow.value = false;
  }

  function cameraSelect(row) {
    realVideoRef.value.changeUrl(row);
  }

  function getAISListLast() {
    aisTrackApi.getListLast().then(({ data }) => {
      mapRef.value.drawAISListLast(data);
    });
  }

  function uploadConfig(type) {
    mapRef.value.uploadConfig(type);
  }

  function changeCamera(row) {
    setTimeout(() => {
      row.currentTime = dateFormat(+new Date());
      mapRef.value.changeCamera(row);
      realVideoRef.value.changeShipInfo(row);
    }, 3 * 1000);
  }

  function stopCamera(id) {
    console.log('id');
  }

  function mqttGetWaterValue(row) {
    const waterEq = {
      value: row || 22,
    };
    mapRef.value.showWatchPoint(waterEq);
  }

  function mqttGetWatchRecord() {
    watchRecordRef.value.getBlackByMqtt();
  }

  function eventHistory(type) {
    eventCountRef.value.open(type);
  }

  function eventIllegal(id) {
    followRef.value.deleteDataByMqtt(id);
    alarmRef.value.deleteDataByMqtt(id);
  }

  function devicePing(row) {
    deviceRef.value.changeStatus(row);
  }

  function blackSelect(row) {
    mapRef.value.drawBlackLine(row);
  }

  function getBlackList() {
    useUserStore().getBlackList();
  }

  onMounted(() => {
    initMqtt();
    getFlickerArea();
    // 获取黑名单
    getBlackList();
  });
  // onMounted(getAISListLast);
</script>

<style lang="less" scoped>
  @import './index.less';
</style>
